package org.hxzon.tapestry5.components;

import java.util.Date;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.base.AbstractField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.hxzon.util.DateFormatUtil;

@Import(library = { "DateFieldEx.js" })
public class DateFieldEx extends AbstractField {
    @Parameter(name = "value", required = true, principal = true)
    @Property
    private Date _value;

    private final String _format = "yyyy-MM-dd";

    @Inject
    private Request _request;

    @Environmental
    private JavaScriptSupport _jsSupport;

    @Inject
    private ComponentResources _resources;

    void beginRender(MarkupWriter writer) {
        String clientId = getClientId();
        String value = DateFormatUtil.format(_value, _format);
        writer.element("input", "type", "text", "name", getControlName(), "id", clientId, "readonly", "readonly", "value", value);
        writeDisabled(writer);
        _resources.renderInformalParameters(writer);
        decorateInsideField();
        writer.end();//input

        JSONObject spec = new JSONObject();

        spec.put("field", clientId);
//        spec.put("date", value);
        _jsSupport.addInitializerCall("DateFieldEx", spec);
    }

    private void writeDisabled(MarkupWriter writer) {
        if (isDisabled()) {
            writer.attributes("disabled", "disabled");
        }
    }

    @Override
    protected void processSubmission(String controlName) {
        this._value = DateFormatUtil.parse(_request.getParameter(controlName), _format);
    }

}
